package controllers

import (
	"fmt"
	"log"
	"net/http"
	"strconv"
	"sync"
	"time"

	"ix-brow/models"
	"ix-brow/services"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

// 代理列表响应体
type ProxyResponse struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

// 创建代理请求体
type CreateProxyRequest struct {
	ProxyType     string `json:"proxyType" binding:"required"`
	ProxyIP       string `json:"proxyIP" binding:"required"`
	ProxyPort     string `json:"proxyPort" binding:"required"`
	ProxyUser     string `json:"proxyUser"`
	ProxyPassword string `json:"proxyPassword"`
	ProxyTagID    string `json:"proxyTagID"`
	Note          string `json:"note"`
}

// 创建代理API
func CreateProxy(c *gin.Context) {
	var req CreateProxyRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, ProxyResponse{
			Code:    400,
			Message: "无效的请求参数: " + err.Error(),
		})
		return
	}

	// 调用IX浏览器API创建代理
	api := services.NewIxBrowserAPI()
	apiReq := &services.CreateProxyRequest{
		ProxyType:     req.ProxyType,
		ProxyIP:       req.ProxyIP,
		ProxyPort:     req.ProxyPort,
		ProxyUser:     req.ProxyUser,
		ProxyPassword: req.ProxyPassword,
		ProxyTagID:    req.ProxyTagID,
		Note:          req.Note,
	}

	externalID, err := api.CreateProxy(apiReq)
	if err != nil {
		c.JSON(http.StatusInternalServerError, ProxyResponse{
			Code:    500,
			Message: fmt.Sprintf("创建代理失败: %v", err),
		})
		return
	}

	// 创建本地数据库记录
	proxy := &models.Proxy{
		ExternalID:    externalID,
		ProxyType:     req.ProxyType,
		ProxyIP:       req.ProxyIP,
		ProxyPort:     req.ProxyPort,
		ProxyUser:     req.ProxyUser,
		ProxyPassword: req.ProxyPassword,
		TagIDs:        req.ProxyTagID,
		Note:          req.Note,
		Active:        true,
	}

	if err := models.CreateProxy(proxy); err != nil {
		c.JSON(http.StatusInternalServerError, ProxyResponse{
			Code:    500,
			Message: fmt.Sprintf("保存代理信息失败: %v", err),
		})
		return
	}

	c.JSON(http.StatusOK, ProxyResponse{
		Code:    200,
		Message: "代理创建成功",
		Data:    proxy,
	})
}

// 更新代理请求体
type UpdateProxyRequest struct {
	ID            string `json:"id" binding:"required"`
	ProxyType     string `json:"proxyType" binding:"required"`
	ProxyIP       string `json:"proxyIP" binding:"required"`
	ProxyPort     string `json:"proxyPort" binding:"required"`
	ProxyUser     string `json:"proxyUser"`
	ProxyPassword string `json:"proxyPassword"`
	ProxyTagID    string `json:"proxyTagID"`
	Note          string `json:"note"`
}

// 更新代理API
func UpdateProxy(c *gin.Context) {
	var req UpdateProxyRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, ProxyResponse{
			Code:    400,
			Message: "无效的请求参数: " + err.Error(),
		})
		return
	}

	// 解析UUID
	id, err := uuid.Parse(req.ID)
	if err != nil {
		c.JSON(http.StatusBadRequest, ProxyResponse{
			Code:    400,
			Message: "无效的代理ID",
		})
		return
	}

	// 获取当前代理信息
	proxy, err := models.GetProxyByID(id)
	if err != nil {
		c.JSON(http.StatusNotFound, ProxyResponse{
			Code:    404,
			Message: "代理不存在",
		})
		return
	}

	// 调用IX浏览器API更新代理
	api := services.NewIxBrowserAPI()
	apiReq := &services.UpdateProxyRequest{
		ID:            proxy.ExternalID,
		ProxyType:     req.ProxyType,
		ProxyIP:       req.ProxyIP,
		ProxyPort:     req.ProxyPort,
		ProxyUser:     req.ProxyUser,
		ProxyPassword: req.ProxyPassword,
		ProxyTagID:    req.ProxyTagID,
		Note:          req.Note,
	}

	if err := api.UpdateProxy(apiReq); err != nil {
		c.JSON(http.StatusInternalServerError, ProxyResponse{
			Code:    500,
			Message: fmt.Sprintf("更新代理失败: %v", err),
		})
		return
	}

	// 更新本地数据库记录
	proxy.ProxyType = req.ProxyType
	proxy.ProxyIP = req.ProxyIP
	proxy.ProxyPort = req.ProxyPort
	proxy.ProxyUser = req.ProxyUser
	proxy.ProxyPassword = req.ProxyPassword
	proxy.TagIDs = req.ProxyTagID
	proxy.Note = req.Note

	if err := models.UpdateProxy(proxy); err != nil {
		c.JSON(http.StatusInternalServerError, ProxyResponse{
			Code:    500,
			Message: fmt.Sprintf("保存代理信息失败: %v", err),
		})
		return
	}

	c.JSON(http.StatusOK, ProxyResponse{
		Code:    200,
		Message: "代理更新成功",
		Data:    proxy,
	})
}

// 删除代理API
func DeleteProxy(c *gin.Context) {
	idStr := c.Param("id")
	id, err := uuid.Parse(idStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, ProxyResponse{
			Code:    400,
			Message: "无效的代理ID",
		})
		return
	}

	// 获取当前代理信息
	proxy, err := models.GetProxyByID(id)
	if err != nil {
		c.JSON(http.StatusNotFound, ProxyResponse{
			Code:    404,
			Message: "代理不存在",
		})
		return
	}

	// 调用IX浏览器API删除代理
	api := services.NewIxBrowserAPI()
	if err := api.DeleteProxy(proxy.ExternalID); err != nil {
		c.JSON(http.StatusInternalServerError, ProxyResponse{
			Code:    500,
			Message: fmt.Sprintf("删除代理失败: %v", err),
		})
		return
	}

	// 从本地数据库中物理删除记录
	if err := models.DeleteProxy(id); err != nil {
		c.JSON(http.StatusInternalServerError, ProxyResponse{
			Code:    500,
			Message: fmt.Sprintf("删除代理记录失败: %v", err),
		})
		return
	}

	c.JSON(http.StatusOK, ProxyResponse{
		Code:    200,
		Message: "代理删除成功",
	})
}

// 获取代理列表API
func GetProxyList(c *gin.Context) {
	// 解析查询参数
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "10"))
	proxyIP := c.DefaultQuery("proxyIP", "")
	proxyUser := c.DefaultQuery("proxyUser", "")
	proxyType := c.DefaultQuery("proxyType", "")

	// 查询代理列表
	req := &models.ProxyListRequest{
		Page:      page,
		PageSize:  pageSize,
		ProxyIP:   proxyIP,
		ProxyUser: proxyUser,
		ProxyType: proxyType,
	}

	proxies, total, err := models.GetProxyList(req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, ProxyResponse{
			Code:    500,
			Message: fmt.Sprintf("获取代理列表失败: %v", err),
		})
		return
	}

	c.JSON(http.StatusOK, ProxyResponse{
		Code:    200,
		Message: "成功",
		Data: map[string]interface{}{
			"total":    total,
			"list":     proxies,
			"page":     page,
			"pageSize": pageSize,
		},
	})
}

// 获取代理详情API
func GetProxyDetail(c *gin.Context) {
	idStr := c.Param("id")
	id, err := uuid.Parse(idStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, ProxyResponse{
			Code:    400,
			Message: "无效的代理ID",
		})
		return
	}

	// 获取代理详情
	proxy, err := models.GetProxyByID(id)
	if err != nil {
		c.JSON(http.StatusNotFound, ProxyResponse{
			Code:    404,
			Message: "代理不存在",
		})
		return
	}

	c.JSON(http.StatusOK, ProxyResponse{
		Code:    200,
		Message: "成功",
		Data:    proxy,
	})
}

// 同步代理API（从远程获取代理列表并同步到本地）
func SyncProxies(c *gin.Context) {
	// 调用IX浏览器API获取代理列表
	api := services.NewIxBrowserAPI()
	req := &services.GetProxyListRequest{
		Page:  1,
		Limit: 1000, // 假设最多1000个代理
		Type:  0,    // 所有类型
	}

	response, err := api.GetProxyList(req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, ProxyResponse{
			Code:    500,
			Message: fmt.Sprintf("获取代理列表失败: %v", err),
		})
		return
	}

	// 处理同步逻辑
	syncCount := 0
	for _, item := range response.Data.Items {
		// 检查代理是否已存在
		existingProxy, _ := models.GetProxyByExternalID(item.ID)

		if existingProxy != nil {
			// 更新已存在的代理
			existingProxy.ProxyType = item.ProxyType
			existingProxy.ProxyIP = item.ProxyIP
			existingProxy.ProxyPort = item.ProxyPort
			existingProxy.ProxyUser = item.ProxyUser
			existingProxy.ProxyPassword = item.ProxyPassword
			existingProxy.TagIDs = item.ProxyTagID
			existingProxy.Note = item.Note

			if err := models.UpdateProxy(existingProxy); err != nil {
				log.Printf("更新代理失败 (ID: %d): %v", item.ID, err)
				continue
			}
		} else {
			// 创建新代理记录
			newProxy := &models.Proxy{
				ExternalID:    item.ID,
				ProxyType:     item.ProxyType,
				ProxyIP:       item.ProxyIP,
				ProxyPort:     item.ProxyPort,
				ProxyUser:     item.ProxyUser,
				ProxyPassword: item.ProxyPassword,
				TagIDs:        item.ProxyTagID,
				Note:          item.Note,
				Active:        true,
			}

			if err := models.CreateProxy(newProxy); err != nil {
				log.Printf("创建代理失败 (ID: %d): %v", item.ID, err)
				continue
			}
		}

		syncCount++
	}

	c.JSON(http.StatusOK, ProxyResponse{
		Code:    200,
		Message: fmt.Sprintf("同步成功，共同步 %d 个代理", syncCount),
		Data: map[string]interface{}{
			"total":      response.Data.Total,
			"syncCount":  syncCount,
			"remoteList": response.Data.Items,
		},
	})
}

// 应用代理请求体
type ApplyProxyRequest struct {
	ProxyID string   `json:"proxyId" binding:"required"`
	UserIDs []string `json:"userIds" binding:"required"`
}

// 应用结果项
type ApplyResultItem struct {
	Username    string `json:"username"`
	BrowserName string `json:"browserName"`
	BrowserID   string `json:"browserId"`
	Success     bool   `json:"success"`
	Message     string `json:"message"`
}

// 应用代理到多个用户的API
func ApplyProxyToUsers(c *gin.Context) {
	var req ApplyProxyRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, ProxyResponse{
			Code:    400,
			Message: "无效的请求参数: " + err.Error(),
		})
		return
	}

	// 解析代理ID
	proxyID, err := uuid.Parse(req.ProxyID)
	if err != nil {
		c.JSON(http.StatusBadRequest, ProxyResponse{
			Code:    400,
			Message: "无效的代理ID",
		})
		return
	}

	// 获取代理信息
	proxy, err := models.GetProxyByID(proxyID)
	if err != nil {
		c.JSON(http.StatusNotFound, ProxyResponse{
			Code:    404,
			Message: "代理不存在: " + err.Error(),
		})
		return
	}

	// 解析用户ID列表
	var userIDs []uuid.UUID
	for _, idStr := range req.UserIDs {
		id, err := uuid.Parse(idStr)
		if err != nil {
			c.JSON(http.StatusBadRequest, ProxyResponse{
				Code:    400,
				Message: "无效的用户ID: " + idStr,
			})
			return
		}
		userIDs = append(userIDs, id)
	}

	// 创建IX浏览器API客户端
	api := services.NewIxBrowserAPI()

	// 处理结果
	results := make([]ApplyResultItem, 0)
	// 并发控制
	var wg sync.WaitGroup
	var mutex sync.Mutex

	// 用于存储批量创建的代理应用记录
	var proxyApplications []*models.ProxyApplication

	// 处理每个用户
	for _, userID := range userIDs {
		// 获取用户信息
		user, _, browsers, err := models.GetUserByID(userID)
		if err != nil {
			// 添加错误结果
			resultItem := ApplyResultItem{
				Username: "未知用户",
				Success:  false,
				Message:  "获取用户信息失败: " + err.Error(),
			}
			results = append(results, resultItem)

			// 记录应用失败的历史
			proxyApp := &models.ProxyApplication{
				ProxyID: proxyID,
				UserID:  userID,
				Success: false,
				Message: resultItem.Message,
			}
			proxyApplications = append(proxyApplications, proxyApp)
			continue
		}

		// 如果没有浏览器，则跳过
		if len(browsers) == 0 {
			resultItem := ApplyResultItem{
				Username: user.Username,
				Success:  false,
				Message:  "用户没有浏览器",
			}
			results = append(results, resultItem)

			// 记录应用失败的历史
			proxyApp := &models.ProxyApplication{
				ProxyID: proxyID,
				UserID:  userID,
				Success: false,
				Message: resultItem.Message,
			}
			proxyApplications = append(proxyApplications, proxyApp)
			continue
		}

		// 处理每个浏览器
		for _, browser := range browsers {
			wg.Add(1)
			go func(u *models.User, b models.Browser) {
				defer wg.Done()

				var resultItem ApplyResultItem
				var proxyApp *models.ProxyApplication

				// 初始化结果和记录对象
				resultItem = ApplyResultItem{
					Username:    u.Username,
					BrowserName: b.BrowserName,
					BrowserID:   b.ID.String(),
					Success:     false,
					Message:     "",
				}

				proxyApp = &models.ProxyApplication{
					ProxyID:     proxyID,
					UserID:      u.ID,
					BrowserID:   b.ID,
					BrowserName: b.BrowserName,
					Success:     false,
				}

				// 检查浏览器是否活跃
				if !b.Active {
					resultItem.Message = "浏览器已禁用"
					proxyApp.Message = resultItem.Message

					mutex.Lock()
					results = append(results, resultItem)
					proxyApplications = append(proxyApplications, proxyApp)
					mutex.Unlock()
					return
				}

				// 检查浏览器是否过期
				if b.ExpirationTime.Before(time.Now()) {
					resultItem.Message = "浏览器已过期"
					proxyApp.Message = resultItem.Message

					mutex.Lock()
					results = append(results, resultItem)
					proxyApplications = append(proxyApplications, proxyApp)
					mutex.Unlock()
					return
				}

				// 只有当浏览器有外部ID时才更新
				if b.ExternalBrowserID <= 0 {
					resultItem.Message = "浏览器没有外部ID"
					proxyApp.Message = resultItem.Message

					mutex.Lock()
					results = append(results, resultItem)
					proxyApplications = append(proxyApplications, proxyApp)
					mutex.Unlock()
					return
				}

				// 创建更新代理的请求
				proxyRequest := &services.UpdateBrowserProxyRequest{
					ProfileID: b.ExternalBrowserID,
				}
				proxyRequest.ProxyInfo.ProxyMode = 2 // 直连模式改为代理模式
				proxyRequest.ProxyInfo.ProxyCheckLine = "global_line"
				proxyRequest.ProxyInfo.ProxyType = proxy.ProxyType
				proxyRequest.ProxyInfo.ProxyIP = proxy.ProxyIP
				proxyRequest.ProxyInfo.ProxyPort = proxy.ProxyPort
				proxyRequest.ProxyInfo.ProxyUser = proxy.ProxyUser
				proxyRequest.ProxyInfo.ProxyPassword = proxy.ProxyPassword

				// 调用API更新浏览器代理
				err := api.UpdateBrowserProxy(proxyRequest)
				if err != nil {
					resultItem.Message = "更新代理失败: " + err.Error()
					proxyApp.Message = resultItem.Message

					mutex.Lock()
					results = append(results, resultItem)
					proxyApplications = append(proxyApplications, proxyApp)
					mutex.Unlock()
					return
				}

				// 设置成功结果
				resultItem.Success = true
				resultItem.Message = "代理应用成功"
				proxyApp.Success = true
				proxyApp.Message = resultItem.Message

				mutex.Lock()
				results = append(results, resultItem)
				proxyApplications = append(proxyApplications, proxyApp)
				mutex.Unlock()
			}(user, browser)
		}
	}

	// 等待所有协程完成
	wg.Wait()

	// 批量保存代理应用记录
	if len(proxyApplications) > 0 {
		if err := models.BatchCreateProxyApplications(proxyApplications); err != nil {
			log.Printf("保存代理应用记录失败: %v", err)
		} else {
			log.Printf("已保存 %d 条代理应用记录", len(proxyApplications))
		}
	}

	// 返回结果
	c.JSON(http.StatusOK, ProxyResponse{
		Code:    200,
		Message: fmt.Sprintf("代理应用处理完成，共 %d 个结果", len(results)),
		Data:    results,
	})
}

// 获取代理应用历史API
func GetProxyApplicationHistory(c *gin.Context) {
	// 解析查询参数
	proxyIDStr := c.Query("proxyId")
	userIDStr := c.Query("userId")
	limitStr := c.DefaultQuery("limit", "50")

	limit, err := strconv.Atoi(limitStr)
	if err != nil || limit <= 0 || limit > 100 {
		limit = 50 // 默认限制为50条记录
	}

	var proxyID, userID uuid.UUID

	// 解析代理ID
	if proxyIDStr != "" {
		proxyID, err = uuid.Parse(proxyIDStr)
		if err != nil {
			c.JSON(http.StatusBadRequest, ProxyResponse{
				Code:    400,
				Message: "无效的代理ID",
			})
			return
		}
	}

	// 解析用户ID
	if userIDStr != "" {
		userID, err = uuid.Parse(userIDStr)
		if err != nil {
			c.JSON(http.StatusBadRequest, ProxyResponse{
				Code:    400,
				Message: "无效的用户ID",
			})
			return
		}
	}

	// 获取应用历史记录
	history, err := models.GetProxyApplications(userID, proxyID, limit)
	if err != nil {
		c.JSON(http.StatusInternalServerError, ProxyResponse{
			Code:    500,
			Message: fmt.Sprintf("获取代理应用历史记录失败: %v", err),
		})
		return
	}

	c.JSON(http.StatusOK, ProxyResponse{
		Code:    200,
		Message: "成功",
		Data: map[string]interface{}{
			"total": len(history),
			"list":  history,
		},
	})
}

// GetAllBrowsersForProxy 获取所有可应用代理的浏览器列表
func GetAllBrowsersForProxy(c *gin.Context) {
	// 调用模型层函数，传入可能为 Nil 的 proxyID
	browsers, err := models.GetAllActiveBrowsersForProxyApplication()
	if err != nil {
		c.JSON(http.StatusInternalServerError, ProxyResponse{
			Code:    500,
			Message: fmt.Sprintf("获取浏览器列表失败: %v", err),
		})
		return
	}

	c.JSON(http.StatusOK, ProxyResponse{
		Code:    200,
		Message: "成功",
		Data:    browsers,
	})
}

// 应用代理到浏览器请求体
type ApplyProxyToBrowsersRequest struct {
	ProxyID    string   `json:"proxyId" binding:"required"`
	BrowserIDs []string `json:"browserIds" binding:"required"`
}

// ApplyProxyToBrowsers 将代理应用到指定的浏览器列表
func ApplyProxyToBrowsers(c *gin.Context) {
	var req ApplyProxyToBrowsersRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, ProxyResponse{
			Code:    400,
			Message: "无效的请求参数: " + err.Error(),
		})
		return
	}

	// 解析代理ID
	proxyID, err := uuid.Parse(req.ProxyID)
	if err != nil {
		c.JSON(http.StatusBadRequest, ProxyResponse{
			Code:    400,
			Message: "无效的代理ID",
		})
		return
	}

	// 获取代理信息
	proxy, err := models.GetProxyByID(proxyID)
	if err != nil {
		c.JSON(http.StatusNotFound, ProxyResponse{
			Code:    404,
			Message: "代理不存在: " + err.Error(),
		})
		return
	}
	log.Printf("准备将代理 %s (%s:%s) 应用到浏览器...", proxy.ID, proxy.ProxyIP, proxy.ProxyPort)

	// 解析浏览器ID列表
	var browserIDs []uuid.UUID
	for _, idStr := range req.BrowserIDs {
		id, err := uuid.Parse(idStr)
		if err != nil {
			c.JSON(http.StatusBadRequest, ProxyResponse{
				Code:    400,
				Message: "无效的浏览器ID: " + idStr,
			})
			return
		}
		browserIDs = append(browserIDs, id)
	}
	log.Printf("目标浏览器ID数量: %d", len(browserIDs))

	// 创建IX浏览器API客户端
	api := services.NewIxBrowserAPI()

	// 处理结果
	results := make([]ApplyResultItem, 0)
	// 并发控制
	var wg sync.WaitGroup
	var mutex sync.Mutex

	// 用于存储批量创建的代理应用记录
	var proxyApplications []*models.ProxyApplication

	// 处理每个浏览器ID
	for _, browserID := range browserIDs {
		wg.Add(1)
		go func(bID uuid.UUID) {
			defer wg.Done()

			log.Printf("开始处理浏览器 ID: %s", bID)

			var resultItem ApplyResultItem
			var proxyApp *models.ProxyApplication

			// 获取浏览器完整信息
			var browser models.Browser
			if err := models.DB.First(&browser, "id = ?", bID).Error; err != nil {
				log.Printf("[错误] 获取浏览器信息失败 (ID: %s): %v", bID, err)
				resultItem = ApplyResultItem{
					BrowserID: bID.String(),
					Success:   false,
					Message:   "获取浏览器信息失败: " + err.Error(),
				}
				proxyApp = &models.ProxyApplication{
					ProxyID:   proxyID,
					BrowserID: bID,
					Success:   false,
					Message:   resultItem.Message,
				}
				mutex.Lock()
				results = append(results, resultItem)
				proxyApplications = append(proxyApplications, proxyApp)
				mutex.Unlock()
				return
			}
			log.Printf("获取到浏览器: 名称=%s, 类型=%s, ExternalID=%d, Active=%t, Exp=%s",
				browser.BrowserName, browser.BrowserType, browser.ExternalBrowserID, browser.Active, browser.ExpirationTime)

			// 获取关联的用户信息 (用于记录)
			var user models.User
			var group models.Group
			if err := models.DB.First(&group, "id = ?", browser.GroupID).Error; err == nil {
				models.DB.First(&user, "id = ?", group.UserID)
			}

			// 初始化结果和记录对象
			resultItem = ApplyResultItem{
				Username:    user.Username, // 可能为空，如果找不到用户
				BrowserName: browser.BrowserName,
				BrowserID:   browser.ID.String(),
				Success:     false,
				Message:     "",
			}

			proxyApp = &models.ProxyApplication{
				ProxyID:     proxyID,
				UserID:      user.ID, // 可能为 Nil
				BrowserID:   browser.ID,
				BrowserName: browser.BrowserName,
				Success:     false,
			}

			// === 执行检查 ===
			if !browser.Active {
				resultItem.Message = "浏览器已禁用"
				log.Printf("[跳过] 浏览器 %s (%s) 已禁用", browser.ID, browser.BrowserName)
			} else if browser.ExpirationTime.Before(time.Now()) {
				resultItem.Message = "浏览器已过期"
				log.Printf("[跳过] 浏览器 %s (%s) 已过期 (%s)", browser.ID, browser.BrowserName, browser.ExpirationTime)
			} else if browser.ExternalBrowserID <= 0 {
				resultItem.Message = "浏览器没有有效的外部ID"
				log.Printf("[跳过] 浏览器 %s (%s) 没有外部ID (%d)", browser.ID, browser.BrowserName, browser.ExternalBrowserID)
			} else {
				// === 调用API更新代理 ===
				log.Printf("准备调用API更新浏览器 %s (ExternalID: %d) 的代理...", browser.ID, browser.ExternalBrowserID)
				proxyRequest := &services.UpdateBrowserProxyRequest{
					ProfileID: browser.ExternalBrowserID,
				}
				proxyRequest.ProxyInfo.ProxyMode = 2 // 代理模式
				proxyRequest.ProxyInfo.ProxyCheckLine = "global_line"
				proxyRequest.ProxyInfo.ProxyType = proxy.ProxyType
				proxyRequest.ProxyInfo.ProxyIP = proxy.ProxyIP
				proxyRequest.ProxyInfo.ProxyPort = proxy.ProxyPort
				proxyRequest.ProxyInfo.ProxyUser = proxy.ProxyUser
				proxyRequest.ProxyInfo.ProxyPassword = proxy.ProxyPassword

				err := api.UpdateBrowserProxy(proxyRequest)
				if err != nil {
					resultItem.Message = "更新代理失败: " + err.Error()
					log.Printf("[错误] 更新浏览器 %s (%s) 代理失败: %v", browser.ID, browser.BrowserName, err)
				} else {
					resultItem.Success = true
					resultItem.Message = "代理应用成功"
					proxyApp.Success = true
					log.Printf("[成功] 更新浏览器 %s (%s) 代理成功", browser.ID, browser.BrowserName)
				}
			}

			// 记录结果和历史
			proxyApp.Message = resultItem.Message
			mutex.Lock()
			results = append(results, resultItem)
			proxyApplications = append(proxyApplications, proxyApp)
			mutex.Unlock()
		}(browserID)
	}

	// 等待所有协程完成
	wg.Wait()
	log.Printf("所有浏览器处理协程已完成")

	// 批量保存代理应用记录
	if len(proxyApplications) > 0 {
		if err := models.BatchCreateProxyApplications(proxyApplications); err != nil {
			log.Printf("[错误] 批量保存代理应用记录失败: %v", err)
			// 注意：这里不返回错误给前端，因为主要操作可能已部分成功
		} else {
			log.Printf("成功批量保存 %d 条代理应用记录", len(proxyApplications))
		}
	}

	// 返回结果
	c.JSON(http.StatusOK, ProxyResponse{
		Code:    200,
		Message: fmt.Sprintf("代理应用处理完成，共处理 %d 个浏览器", len(results)),
		Data:    results,
	})
}
